package online.chazi.bootplus.commons.utils;

import org.apache.commons.codec.digest.DigestUtils;

import java.util.Map;
import java.util.TreeMap;

/**
 * 说明：这个是小程序签名排序的算法。按ASCii自然排序。
 * 如：
 * 请求参数：name=chazi&age=18&height=170
 * 排序之后：age=18&height=170&name=chazi
 * 最后加密的串是stringA：age=18&height=170&name=chazi&signKeyAppended
 * 输出加密数据是signature：md5Hex(stringA)
 * Created by 叉子同学 on 2020-03-27 19:16
 */
public class SignMapUtils {

    //signKeyAppended = "key=" + signKey
    public static String getSignature(Map<String, String> map, String signKeyAppended) {
        return DigestUtils.md5Hex(getStringA(map, signKeyAppended));
    }

    public static TreeMap<String, String> sortMap(Map<String, String> map) {
        TreeMap<String, String> signMap = new TreeMap<>(String::compareTo);
        map.forEach(signMap::put);
        return signMap;
    }

    public static String getStringA(Map<String, String> map, String appended) {
        TreeMap<String, String> signMap = sortMap(map);
        return getStringA(appended, signMap);
    }

    public static String getStringA(String appended, TreeMap<String, String> treeMap) {
        StringBuffer sb = new StringBuffer();
        treeMap.forEach((k, v) -> {
            sb.append(k).append("=").append(v).append("&");
        });
        return sb.append(appended).toString();
    }

}
